﻿using System.IO.IsolatedStorage;

namespace IsoStorageManagerLib
{
    public partial class IsoStorageManager
    {
        private static readonly IsolatedStorageSettings isoSettings = IsolatedStorageSettings.ApplicationSettings;

        /// <summary>
        /// Set a property
        /// </summary>
        /// <param name="key"></param>
        /// <param name="content"></param>
        public static void SetSettingsProperty(string key, object content)
        {
            if (content == null)
                RemoveSettingsProperty(key);

            isoSettings[key] = content;
            isoSettings.Save();
        }

        /// <summary>
        /// Get object from IsolatedStorageSettings. 
        /// WARNING: returns null, if property is not found.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object GetSettingsProperty(string key)
        {
            if (isoSettings.Contains(key) && isoSettings[key] != null)
                return isoSettings[key];

            return null;
        }

        /// <summary>
        /// Gets a value for the specified key
        /// </summary>
        /// <typeparam name="T">The System.Type of the value parameter.</typeparam>
        /// <param name="key">The key of the value to get.</param>
        /// <param name="default">A value to return if the key is not found.</param>
        /// <returns></returns>
        public static T TryGetSettingsProperty<T>(string key, T @default)
        {
            T value;
            return isoSettings.TryGetValue(key, out value) ? value : @default;
        }

        /// <summary>
        /// Removes property, if already exists
        /// </summary>
        /// <param name="key"></param>
        public static void RemoveSettingsProperty(string key)
        {
            if (isoSettings.Contains(key))
                isoSettings.Remove(key);
        }
    }
}
